#include "my_server.hpp"

using namespace eiennet;
using namespace std;
using namespace winux;

MyServer::MyServer( std::string const& path, uint port)
    : path(path),
      server("", port, 10, 10, 0.1)
{
    //todo: 做房间列表
    room = new Room(this);

    server.onOpenHandler([this](SharedPointer<UserClientCtx> userClientPtr) {
        string url = userClientPtr->url.getPath();
        if (url == this->path)
        {
            auto &user = userClientPtr->user;
            user.init(this);
            addUser(&user);
        }
    });
    server.onCloseHandler([this](SharedPointer<UserClientCtx> userClientPtr, winux::uint16 errCode, winux::AnsiString const &errStr) {
        string url = userClientPtr->url.getPath();
        if (url == this->path)
        {
            auto &user = userClientPtr->user;
            TRACE("[func] erver.onCloseHandler {0}", user.uid );
            user.destroy();
            delUser(user.uid);
        }
    });
    server.onMessageHandler([this](SharedPointer<UserClientCtx> userClientPtr, AnsiString const &data, int type) {
        string url = userClientPtr->url.getPath();
        if (url == this->path)
        {
            auto &user = userClientPtr->user;
            user.onMessage(data);
        }
    });
}

MyServer::~MyServer()
{
    delete room;
}

void MyServer::userEnterRoom(User *user)
{
    room->addUser(user);
}
void MyServer::run()
{
    server.run();
}

winux::Mixed MyServer::getInfo()
{
    return Mixed();
}